var counter = 0;
var highestIdProcessed = -1;
var currentWord;
var player;
var needsToBeSaved = false;
var ended = false;

function keyevent(evt){
	if (evt.keyCode == 37){
		if (times.length > 0){
			times.pop();		
			//alert(currentWord);
			if (currentWord != null)
				currentWord.style.fontWeight = "normal";
			selectPreviousWord();
		}
	}
	else if (evt.keyCode == 39){
		// round to two decimal places and save
		var time = Math.round(player.currentTime * 100) / 100;
		times.push(time);
		if (currentWord != null)
			currentWord.style.fontWeight = "normal";
		selectNextWord();
		needsToBeSaved = true;
	}
	else if (evt.keyCode == 80){
		if (playing){
			pause();
		}
		else{
			play();			
		}
	}
	else if (evt.keyCode == 70){
		alert(times);
	}
}

var playing = false;
var playbackRate = .8;
var preSelectFirstWord  = true;
function play(){
	var begin = document.getElementById("begin");
	begin.disabled=true;
	if (preSelectFirstWord && (times == null || times.length == 0)){
		times.push(.1);
		selectNextWord();
	}
	begin.innerHTML = "Play";
	var pause = document.getElementById("pause");
	pause.disabled=false;
	playing = true;
	player.play();
	player.playbackRate = playbackRate;
}

function pause(){
	var begin = document.getElementById("begin");
	begin.disabled=false;
	var pause = document.getElementById("pause");
	pause.disabled=true;
	player.pause();
	playing = false;
	if (needsToBeSaved){
		enableSaveButtons();
	}
}

var configed = false;
function configMediaPlayer(){
alert("confi" + player);
	if (!configed){
		configed = true;
//		alert("configMediaPlayer()");
		if (times.length > 0){
			var lastIndexToBeRecorded = times.length - 1;
			//alert(times[lastIndexToBeRecorded])
		//	alert("w" + lastIndexToBeRecorded);
			counter = lastIndexToBeRecorded + 1;
			if (hasWordGranularity){
				currentWord =  document.getElementById("w" + lastIndexToBeRecorded);
			}else{
				currentWord =  document.getElementById("s" + lastIndexToBeRecorded);
			}
	//		alert(lastWord);
			if (currentWord != null){
				currentWord.style.fontWeight = "bold";
				player.currentTime= times[lastIndexToBeRecorded];
				alert(times[lastIndexToBeRecorded]);
			}
		}
	}
}

function verifyBrowserCompatibility(){
	var agent = navigator.userAgent;
	///user/readings/demoSound.jsp?id=6
	/*if ( agent.indexOf("Safari") == -1 || agent.indexOf("Chrome") != -1){
		checkinAndExit();
		alert("The sound integration task requires the use of the Safari web browser at this time.");
		window.location = "/eng/volunteering.html"
		return false;
	}*/
	return true;
}

function init(){
	verifyBrowserCompatibility();
	player =  document.getElementById('player');
	if (player == null){
		alert("plaer null");
		 var audioElements =  document.getElementsByTagName('audio');
		 if (audioElements != null){
			 player = audioElements[0];
		 }
		 else{
			var videoElements =  document.getElementsByTagName('video');
			player = videoElements[0];
		 }
	}
	
	player.addEventListener("canplaythrough", configMediaPlayer, false);
	//configMediaPlayer();
	player.addEventListener("ended", onEndMediaPlayer, true);	
	alert("test");
	configMediaPlayer();
}


function onEndMediaPlayer(){
	ended = true;
	pause();
}
function selectNextWord(){
	highestIdProcessed = counter;
	var id;
	if (hasWordGranularity){
		id = "w" + counter++;
	}
	else{
		id = "s" + counter++;
	}
	currentWord = document.getElementById(id);
	if (currentWord != null){ //verify we haven't gotten to the end of the documents
		currentWord.style.fontWeight = "bold";
	}
}

function selectPreviousWord(){
	alert(counter);
	highestIdProcessed = --counter;
		alert(counter);
	var id;
	if (hasWordGranularity){
		id = "w" + (counter -1);
	}
	else{
		id = "s" + (counter - 1);
	}
	currentWord = document.getElementById(id);
	if (currentWord != null){ //verify we haven't gotten to the end of the documents
		currentWord.style.fontWeight = "bold";
	}
}

function shiftTimes(arrayToCopy, subtractBy){
	var size = arrayToCopy.length;
	var newArray = new Array()
	var startingIndex = 704;
	for (y = 0; y < arrayToCopy.length; y++){
		var newValue;
		if (y > startingIndex){
			newValue = arrayToCopy[y] - Number(subtractBy);
			newValue = Math.round(newValue * 100) / 100;
		}
		else{
			newValue = arrayToCopy[y];
		}
		//alert(newValue);
		newArray.push(newValue);
	}
	return newArray;
}

/*function saveExit(){
	save2();
	//window.location="/user/readings/sound2.jsp?id=" + id;
}*/

function save(){
	saveTimes(times);
	/*if (ended){
		var newTimes = shiftTimes(times, .1);
		saveTimes(newTimes);
	}
	else{
		
	}*/
}
function disableSaveButtons(){
	var saveButton = document.getElementById("save");
	saveButton.disabled=true;
	//var continueButton = document.getElementById("continue");
	//continueButton.disabled=false;
}
function enableSaveButtons(){
	var saveButton = document.getElementById("save");
	saveButton.disabled=false;
}

function saveTimes(timesToSave){
	var message = document.getElementById("message");
	message.innerHTML = "Saving..." + timesToSave.toString();
	$.ajax({
  type: 'POST',
  url: "/user/readings/sound_save.jsp",
  data: {id: id, times: timesToSave.toString(), highestIdProcessed: highestIdProcessed},
  success: function(msg) {
	//var saveButton = document.getElementById("save_button");
	disableSaveButtons();
	var message = document.getElementById("message");
	message.innerHTML = "";
	//saveButton.disabled = true;
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
	needsToBeSaved = false;
}

function checkinAndExit(){
	var message = document.getElementById("message");
	message.innerHTML = "Exiting...";
	var exitButton = document.getElementById("exit");
	exitButton.disabled = true;
	$.ajax({
  type: 'POST',
  url: "/user/readings/checkin_sound.jsp",
  data: {id: id},
  success: function(msg) {
	window.location = "/user/readings/reading_view.jsp?id=" + id;
  },
  error:function(request,error){ alert("An error occurred while saving: " + error); },
  dataType: "xml"
});	
}

function continueOn(){
	window.location = "/user/readings/sound2.jsp?id=" + id;
}

function tryToExit(){
	if (needsToBeSaved){
		$("#confirmation").dialog({
			modal: true,
			title: useroptionString,
			buttons: { 
			"Cancel": function() { $(this).dialog("close"); },
			"Exit": function() { $(this).dialog("close"); checkinAndExit() }
			}
		});
	}
	else{
		checkinAndExit();
	}
}
